package com.example.equipment.controller;

import com.example.equipment.annotation.IgnoreCheck;
import com.example.equipment.bean.enums.ResultEnum;
import com.example.equipment.bean.User;
import com.example.equipment.bean.config.OpenApiResult;
import com.example.equipment.service.UserService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private UserService userService;
    private Gson gson = new GsonBuilder().create();

    @IgnoreCheck
    @PostMapping("/login")
    public OpenApiResult login(@RequestBody User req, HttpServletRequest httpServletRequest) {
        log.info("==> LoginController.login(). req={}", req == null ? "" : gson.toJson(req));
        User user = userService.getUserByNameWithPwd(req.getName(), req.getPassword());
        if (user != null) {
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(60*60);//一小时失效
            return OpenApiResult.ok();
        } else {
            return new OpenApiResult(ResultEnum.LOGIN_FAILED);
        }
    }

    @IgnoreCheck
    @GetMapping("/logout")
    public OpenApiResult logout( HttpServletRequest httpServletRequest) {
        log.info("==> LoginController.logout()");
            HttpSession session = httpServletRequest.getSession();
            session.removeAttribute("user");
            return OpenApiResult.ok();
    }
}
